<?php

class EvaksController extends Controller {

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    public function actionStatistics() {
        $evakID = isset($_GET['id']) ? (int) $_GET['id'] : Evaks::model()->find('evak_user = \'' . Yii::app()->user->id . '\' order by evak_id')->evak_id;
        $logs = EvakLog::model()->findAll('evak_id = ' . $evakID . ' order by log_id');
        //echo $evakID;exit;
        $sql = 'SELECT
                        s.evstat_payable,
                        l.status_log_begin,
                        l.status_log_end,	
                        c.city_price
                FROM
                        ev_users u
                JOIN ev_evaks e ON u.user_id = e.evak_user :: INT
                JOIN ev_evak_log l ON e.evak_id = l.evak_id :: INT
                JOIN ev_evstats s ON l.evak_status_id = s.evstat_id
                JOIN ev_cities C ON e.evak_city = c.city_id
                WHERE
                       
                l.evak_id :: INT = ' . $evakID . ' ORDER BY l.status_log_begin DESC';
        $data = array();
        $models = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
        foreach ($models as $model) {
            $data[date('d.m.Y', $model['status_log_begin'])][] = $model;
        }

        $this->render('statistics', array('logs' => $logs, 'evakID' => $evakID, 'data' => $data));
    }

    public function actionChangeStatus() {
        foreach ($_POST['ids'] as $id) {
            $model = $this->loadModel($id);
            if ($model->evak_status != 0 && $model->evak_status != 5) {
                $model->evak_status = $_POST['stats'];
                $model->save(false);
                $time = time();
                $log = EvakLog::model()->find('evak_id = ' . $id . ' order by log_id desc');
                if ($log !== NULL) {
                    $beginTime = $log->status_log_begin;
                    $log->status_log_end = $time;
                    $log->save(false);
                    $endTime = $log->status_log_end;
                    $range = $endTime - $beginTime;
                    $cityPrice = $log->evak->city->city_price;
                    $stat = $log->status;
                    $cost = $stat->evstat_payable ? $this->calculateSumm($range, $cityPrice) : 0;
                    $userBalance = $this->getUser(Yii::app()->user->id, 'user_balance');
                    $this->updateUser(Yii::app()->user->id, 'user_balance', $userBalance - $cost);
                }
                $data = array('evak_id' => $id, 'evak_status_id' => $_POST['stats'], 'status_log_begin' => $time);
                Yii::app()->db->getCommandBuilder()->createInsertCommand('{{evak_log}}', $data)->execute();
            }
        }
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Evaks;
        $this->pageTitle = 'Cоздать пользователя';
        $model->scenario = 'create';
        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Evaks'])) {
            $model->attributes = $_POST['Evaks'];
            if ($model->save()) {
                $this->redirect(array('site/index'));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        $this->performAjaxValidation($model);

        if (isset($_POST['Evaks'])) {
            $model->attributes = $_POST['Evaks'];

            if ($model->save()) {
                $this->redirect(array('index'));
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        $this->loadModel($id)->delete();
        if (!isset($_GET['ajax'])) {
            $this->redirect(array('index'));
        }
    }

    public function actionDeleteArr() {
        $ids = $_POST['ids'];
        foreach ($ids as $id)
            $this->loadModel($id)->delete();
        if (!isset($_GET['ajax'])) {
            $this->redirect(array('index'));
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Users');
        $this->pageTitle = 'Список пользователей';
        $model = new Evaks();

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Evaks'])) {
            $model->attributes = $_POST['Evaks'];
            if ($model->save()) {
                $this->redirect(array('index'));
            }
        }
        $c = new CDbCriteria();
        $c->order = 'evak_id desc';
        $models = Evaks::model()->findAll($c);
        $this->render('index', array(
            'model' => $model,
            'models' => $models
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Users('search');
        $this->pageTitle = 'Управление пользователями';
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Users'])) {
            $model->attributes = $_GET['Users'];
        }

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return Users the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = Evaks::model()->findByPk($id);
        if ($model === null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param Users $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'users-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
